import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ActivatedRoute} from '@angular/router';

export class NewsComment {
  title: string;
  content: string;
  newsId: string;

  constructor(title: string = '', content: string = '', newsId: string = '') {
    this.title = title;
    this.content = content;
    this.newsId = newsId;
  }
}

@Component({
  selector: 'app-news-detail',
  templateUrl: './news-detail.component.html',
  styleUrls: ['./news-detail.component.css']
})
export class NewsDetailComponent implements OnInit {
  news: object;
  comments: any;
  commentSubject = new NewsComment();

  constructor(private http: HttpClient, private activatedRoute: ActivatedRoute) {
    const id = this.activatedRoute.snapshot.params['id'];
    if (id !== undefined && id !== '0') {
      this.http.get(`/news/${id}`).subscribe(result => this.news = result);
      this.getComments(id);
      this.commentSubject.newsId = id;
    }
  }

  getComments(newsId: string) {
    this.http.get(`/news/comment/${newsId}/list`).subscribe(res => {
      this.comments = res;
    });
  }

  submitComment() {
    if (this.commentSubject.title.length === 0 || this.commentSubject.content.length === 0) {
      alert('标题或者评论内容不能为空');
      return;
    }
    if (this.commentSubject.title.length > 64) {
      alert('标题过长');
      return;
    }
    if (this.commentSubject.content.length > 1024) {
      alert('评论内容过长');
      return;
    }
    this.http.post('/news/comment/submit', this.commentSubject)
      .subscribe(res => {
        alert(res['message']);
        if (res['success']) {
          this.getComments(this.commentSubject.newsId);
          this.commentSubject = new NewsComment();
        }
      }, error => {
        alert(error.error['message']);
      });
  }

  ngOnInit() {
  }

}
